package dao;

import model.ExpressSender;
import util.ArgsList;
import util.JDBCConnection;
import util.JDBCFactory;
import util.ResultList;

import java.sql.SQLException;
import java.util.List;

public class ExpressSendersManager implements ExpressSendersManagement {

    @Override
    public Integer saveOne(ExpressSender sender, UsrTypeManager typeManager) {
        if(typeManager == null) return null;
        if(sender == null  ||  sender.getExp_com_id() == null  ||  sender.getU_id() == null) return null;

        Integer exp_com_id = sender.getExp_com_id();
        try {
            JDBCConnection conn = JDBCFactory.takeJDBC();
            conn.start();

            if(conn.update("insert into t_exp_senders values(?,?)", sender.getU_id(), sender.getExp_com_id()) != 1) exp_com_id = null;
            if(conn.update("insert into t_usertype values(?,?)", sender.getU_id(), typeManager.getUserType(conn, "快递负责人", "派送订单的快递负责人用户")) != 1) exp_com_id = null;

            conn.commit();
            JDBCFactory.returnBack(conn);
            return exp_com_id;
        } catch(SQLException e) {
            System.err.println(e.getMessage());
            return null;
        }
    }

    @Override
    public Integer saveOne(long senderID, int companyID, UsrTypeManager typeManager) {
        if(typeManager == null) return null;

        Integer exp_com_id = companyID;
        try {
            JDBCConnection conn = JDBCFactory.takeJDBC();
            conn.start();

            if(conn.update("insert into t_exp_senders values(?,?)", senderID, companyID) != 1) exp_com_id = null;
            if(conn.update("insert into t_usertype values(?,?)", senderID, typeManager.getUserType(conn, "快递负责人", "派送订单的快递负责人用户")) != 1) exp_com_id = null;

            conn.commit();
            JDBCFactory.returnBack(conn);
            return exp_com_id;
        } catch(SQLException e) {
            System.err.println(e.getMessage());
            return null;
        }
    }

    @Override
    public Integer updateOne(long senderID, int companyID) {
        Integer exp_com_id = companyID;
        try {
            JDBCConnection conn = JDBCFactory.takeJDBC();
            if (conn.update("update t_exp_senders set exp_com_id = ? where u_id = ?", companyID, senderID) != 1)
                exp_com_id = null;
            JDBCFactory.returnBack(conn);

            return exp_com_id;
        } catch(SQLException e) {
            System.err.println(e.getMessage());
            return null;
        }
    }

    @Override
    public Integer deleteOne(long senderID, UsrTypeManager typeManager) {
        if(typeManager == null) return null;
        try {
            JDBCConnection conn = JDBCFactory.takeJDBC();
            conn.start();
            //解除该快递员用户的快递员身份
            Integer count = conn.update("delete from t_usertype where u_id = ? and utyp_id = ?", senderID, typeManager.getUserType(conn, "快递员", "派送订单的快递负责人用户"));
            if (conn.update("delete from t_exp_senders where u_id = ?", senderID) != 1) count = null;
            conn.commit();
            JDBCFactory.returnBack(conn);
            return count;
        } catch(SQLException e) {
            System.err.println(e.getMessage());
            return null;
        }
    }

    @Override
    public boolean deleteByCompany(int companyID, UsrTypeManager typeManager) {
        if(typeManager == null) return false;
        int count = 0;
        boolean succeed = false;
        try {
            JDBCConnection conn = JDBCFactory.takeJDBC();
            conn.start();
            //查询该快递公司下属所有快递员的id
            List<Object[]> senderIDs = conn.query("select u_id from t_exp_senders where exp_com_id = ?", companyID);
            Long utypId = typeManager.getUserType(conn, "快递负责人", "派送订单的快递负责人用户");

            //解除该快递公司下属全部快递员用户的快递员身份
            conn.preparedUpdateBatch("delete from t_usertype where u_id = ? and utyp_id = ?");
            for (Object[] row : senderIDs) conn.addUpdateBatch(row[0], utypId);
            succeed = conn.submitUpdateBatch();
            succeed = succeed && (conn.update("delete from t_exp_senders where exp_com_id = ?", companyID) > 0);
            conn.commit();
            JDBCFactory.returnBack(conn);
            return succeed;
        } catch(SQLException e) {
            System.err.println(e.getMessage());
            return false;
        }
    }

    @Override
    public List<ExpressSender> query(ExpressSender sender, int pageSize, int page) {
        boolean firstCondition = true;

        StringBuilder sql = new StringBuilder("select * from t_exp_senders");
        ArgsList<Object> arg_whereCondition = new ArgsList<>();

        //构造条件
        if(sender != null)
        {
            if(sender.getU_id() != null)
            {
                sql.append(" where u_id = ?");
                arg_whereCondition.add(sender.getU_id());
                firstCondition = false;
            }

            if(sender.getExp_com_id() != null)
            {
                if(!firstCondition) sql.append(" and");
                sql.append(" where exp_com_name = ?");
                arg_whereCondition.add(sender.getExp_com_id());
            }
        }

        if(pageSize > 0  &&  page > 0)
        {
            sql.append(" limit ?, ?");
            arg_whereCondition.add((Integer)((page - 1) * pageSize));
            arg_whereCondition.add((Integer)pageSize);
        }
        try {
            JDBCConnection conn = JDBCFactory.takeJDBC();
            List<ExpressSender> result = getResultList(conn.query(arg_whereCondition, sql.toString()));
            JDBCFactory.returnBack(conn);
            return result;
        } catch(SQLException e) {
            System.err.println(e.getMessage());
            return null;
        }
    }

    @Override
    public List<ExpressSender> query(ExpressSender sender) {
        return query(sender, 0, 0);
    }
    @Override
    public List<ExpressSender> query(int pageSize, int page) {
        return query(null, pageSize, page);
    }
    @Override
    public List<ExpressSender> query() {
        return query(null);
    }
    @Override
    public List<ExpressSender> queryALL() {
        return query();
    }
    @Override
    public List<ExpressSender> queryALL(int pageSize, int page) {
        return query(pageSize, page);
    }

    /**
     * 包装并返回查询到的对象的列表
     * @param list 包含 SQL 行查询结果的列表，Object[]中每一项都是一列的值
     * @return 返回包装好的对象列表
     */
    private static List<ExpressSender> getResultList(List<Object[]> list)
    {
        ExpressSender com = null;

        List<ExpressSender> result = new ResultList<>();

        for(Object[] row : list)
        {
            com = new ExpressSender();

            com.setU_id((Long) row[0]);
            com.setExp_com_id((Integer) row[1]);

            result.add(com);
        }
        return result;
    }
}
